<template>
  <div id='CalcBaseForm'>
    <Splitpanes>
      <!-- 设置字段模式  -->
      <Pane size='35' v-if='isDictShow'>
        <vxe-toolbar perfect>
          <template #buttons>
            <div class='smallToolTitle'>设置字段</div>
            <vxe-button type='text' class='button-blue' icon='vxe-icon-refresh' content='刷新' :loading='tloading' @click='findDictList'></vxe-button>
            <vxe-button type='text' class='button-blue' icon='vxe-icon-square-plus' content='新建' @click='addDictForm'></vxe-button>
          </template>
        </vxe-toolbar>

        <div class='designTable'>
          <vxe-table ref='dictTable' class='mytable-scrollbar'
                     border='inner' align='center' height='auto'
                     :data='dictList' :loading='tloading' @current-change='dictRowClick'
                     :row-config='{ isCurrent: true, isHover: true }'
                     :column-config='{ resizable: true }'
                     resizable show-overflow keep-source>
            <vxe-column field='code' title='字段编码' width='110'></vxe-column>
            <vxe-column field='name' title='字段名称' width='110'></vxe-column>
            <vxe-column field='sx' title='顺序' width='50'></vxe-column>
            <vxe-column title='操作' fixed='right'>
              <template #default='{ row }'>
                <vxe-button type='text' status='danger' icon='vxe-icon-delete' circle v-if="row.isParentEdit == '0'" @click.native='deleteDict(row)'></vxe-button>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </Pane>

      <!-- 设置字段右侧表单 -->
      <Pane size='65' v-if='isDictShow'>
        <div class='toolbartitle'>组件属性</div>
        <el-form ref='dictFormRef' :model='dictForm' :rules='dictFormRule' class='form-input-m' label-width='90px' inline-message v-loading='tloading'>
          <el-row>
            <el-col :span='24'>
              <el-form-item label='字段类型' prop='fieldType'>
                <el-select placeholder='请选择字段类型' :teleported='false' v-model='dictForm.fieldType' style='width: 200px'>
                  <el-option v-for='dict in fieldTypeList' :key='dict.code' :label='dict.name' :value='dict.code'></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span='24' v-if="dictForm.fieldType === 'data_select'">
              <el-form-item label='数据来源' prop='dict'>
                <el-select placeholder='请选择数据来源' :teleported='false' v-model='dictForm.dict' style='width: 200px'>
                  <el-option v-for='dict in interfaceDictList' :key='dict.Interface_url' :label='dict.Interface_name' :value='dict.Interface_url'></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span='24'>
              <el-form-item prop='code' label='字段名'>
                <el-input type='text' v-model='dictForm.code' placeholder='请输入字段名' clearable></el-input>
              </el-form-item>
            </el-col>

            <el-col :span='24'>
              <el-form-item prop='name' label='标题'>
                <el-input type='text' v-model='dictForm.name' placeholder='请输入标题' clearable></el-input>
              </el-form-item>
            </el-col>

            <el-col :span='24'>
              <el-form-item prop='order' label='排序'>
                <el-input-number v-model='dictForm.sx' :min='1' :max='1000' />
              </el-form-item>
            </el-col>

            <el-col :span='24'>
              <el-form-item class='form-footer'>
                <template #default>
                  <el-button type='primary' :disabled="dictForm.isParentEdit == '1'" @click="saveDict('dictFormRef')" v-loading='saveFormLoading'>保存</el-button>
                </template>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </Pane>

      <!-- 设置属性模式  -->
      <Pane size='65' v-if='isDetailShow'>
        <vxe-toolbar perfect>
          <template #buttons>
            <div class='smallToolTitle'>设置属性</div>
            <vxe-button type='text' class='button-blue' icon='vxe-icon-refresh' content='刷新' :loading='lookLoading' @click='findDictDetailList'></vxe-button>
            <vxe-button type='text' class='button-blue' icon='vxe-icon-square-plus' content='新建属性' @click='addDetail()'></vxe-button>
            <vxe-button type='text' class='button-blue' icon='vxe-icon-save' content='保存' @click='saveDetailList' :loading='saveLoading'></vxe-button>
          </template>
        </vxe-toolbar>

        <div class='previewTable'>
          <vxe-table ref='detailTable' class='mytable-scrollbar' border='inner' align='center' height='auto'
                     :data='detailList' :loading='lookLoading'
                     :row-config='{ isCurrent: true, isHover: true }'
                     :column-config='{ resizable: true }'
                     :keyboard-config='{isArrow: true, isTab: true, isEdit: true}'
                     :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }"
                     resizable show-overflow keep-source>
            <vxe-column v-for='(item, index) in dictList' :key='index' :field='item.code' :title='item.name' width='130' :edit-render='{}'>
              <template #default='{ row, rowIndex, column }'>
                <span v-if="item.code == 'isEdit'">{{ row[item.code] === '1' ? '是' : '否' }}</span>
                <span v-else-if="item.fieldType === 'whether'">{{ row[item.code] === '1' ? '是' : '否' }}</span>
                <span v-else-if="item.fieldType === 'data_select'">{{ formatUser(row[item.code]) }}</span>
                <span v-else>{{ row[item.code] }}</span>
              </template>

              <template #edit='{ row, rowIndex, column }'>
                <!--                {{item}}-->
                <!-- 是否删改 开关 -->
                <vxe-switch v-model='row[item.code]' v-if="item.code == 'isEdit'" open-label='是' close-label='否' :open-value='1' :close-value='0'></vxe-switch>
                <vxe-input v-if="item.fieldType === 'text_input'" v-model='row[item.code]' type='text'></vxe-input>
                <vxe-input v-if="item.fieldType === 'number_input'" v-model='row[item.code]' type='number'></vxe-input>
                <vxe-input v-if="item.fieldType === 'date'" :placeholder='row[item.name]' v-model='row[item.code]' type='date' class-name='width-100-percentage' />
                <vxe-switch v-if="item.fieldType === 'whether'" v-model='row[item.code]' open-label='是' close-label='否' open-value='1' close-value='0'></vxe-switch>
                <el-select v-if="item.fieldType === 'data_select'" placeholder='请选择' :teleported='false' v-model='row[item.code]' style='width: 200px'>
                  <el-option v-for='dict in userList' :key='dict.id' :label='dict.realname' :value='dict.id'></el-option>
                </el-select>
              </template>
            </vxe-column>
            <vxe-column field='sx' title='排序' :edit-render='{}'>
              <template #edit='{ row, rowIndex, column }'>
                <vxe-input v-model='row.sx' type='text'></vxe-input>
              </template>
            </vxe-column>

            <vxe-column title='操作' align='center' fixed='right'>
              <template #default='{ row }'>
                <vxe-button type='text' status='danger' icon='vxe-icon-delete' circle v-if='panduanIsEdit(row)' @click.native='deleteDetail(row)'></vxe-button>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </Pane>
    </Splitpanes>
  </div>
</template>

<script setup lang='ts'>
// 引入组件区 ==========
import { getCurrentInstance, reactive, ref } from 'vue';
import { Pane, Splitpanes } from 'splitpanes';
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { AppStore } from '@/stores/store';
import { isEmpty } from 'lodash';

let { proxy }: any = getCurrentInstance();

//暴露属性和方法
defineExpose({
  initPage,
  showDictData,  //切换设置字段模式
  showDetailData //切换设置属性模式
});

// 全局变量定义区 ==========
let store = AppStore();
let isDictShow = ref(true); //默认显示设置字段模式
let isDetailShow = ref(false); //设置属性模式
// 加载状态
let tloading = ref(false); //设置字段表格
let lookLoading = ref(false); //设置属性表格

let dictList: any = reactive([]); //设置字段表格数据
let detailList: any = reactive([]); //设置属性表格数据

// 设计模式表单
let dictForm = reactive({
  id: null,
  pid: '',
  orgId: '',
  code: '',
  name: '',
  grade: 1,
  sx: 1,
  value: '',
  bz: '',
  classify: '',
  isParentEdit: '',
  dict: '',
  dictValue: '',
  fieldType: ''
});

// 设计模式表单校验
let dictFormRule = {
  name: [
    {
      required: true,
      message: '请输入标题',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ]
};

// 设计模式表单 字段类型选择
let fieldTypeList: any = [
  { code: 'text_input', name: '文本输入框' },
  { code: 'number_input', name: '数字输入框' },
  { code: 'date', name: '日期选择框' },
  { code: 'datetime', name: '时间选择框' },
  { code: 'whether', name: '是否选择框' },
  { code: 'data_select', name: '数据选择框' }
];

// 设计模式表单:1：前缀 中缀类型
let ruleTypeList: any = [
  { code: 'gdz', name: '固定值' },
  { code: 'rqz', name: '日期值' }
];
// 设计模式表单 1：后缀类型
let sufTypeList: any = [{ code: 'seq', name: '自增序列' }];

//动态表输入的表属性
let tableColumn: any = reactive([
  { field: 'TABLE_NAME', title: '表名' },
  { field: 'COMMENTS', title: '表说明' }
]);
let tableData: any = reactive([]);
let tableList: any = reactive([]);
let correColumnList: any = reactive([]);


let interfaceDictList: any = reactive([]);
let userList: any = reactive([]);

let detailTable = ref(); //预览模式table表格Ref

let sltDict: any = {}; //接收字段传来的row数据


let tableDataList: any = reactive([]); //选择动态表集合

let saveFormLoading = ref(false);//设置字段 表单 保存按钮
let saveLoading = ref(false);//设置属性 最上册保存按钮 

// 方法定义区 =============
function initPage(row: any) {
  detailList.length = 0;
  sltDict = row;
  findDictList(); //获取设计模式table数据
  getDict();
  findUserList();
  // getUrlList()
}

function getDict() {
  interfaceDictList.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http.get(url, { params: { code: 'yhlb' } }).then((res: any) => {
    interfaceDictList.push(...res.data);
  }).catch((err: any) => {
    proxy.$alert(err, '提示');
  });
}

function getUrlList(url: string) {
  // proxy.$http.get("/wk/calc/item/getCalcItemList").then((res: any) => {
  //   return res.data.records
  // }).catch((err: any) => {
  //   proxy.$alert(err, '提示');
  // });
  return [{ code: '1', name: '华雄' }, { code: '2', name: '夏侯' }, { code: '3', name: '潘凤' }];
}

function findUserList() {
  userList.length = 0;
  const url = '/api/user/getUserPageList';
  proxy.$http.get(url, { params: { pageIndex: 0, pageSize: 50 } }).then((res: any) => {
    userList.push(...res.data.records);
  }).catch((err: any) => {
    proxy.$alert(err, '提示');
  });
}


/**
 * 设计模式/预览模式切换 切换设计模式
 */
function showDictData() {
  isDictShow.value = true;
  isDetailShow.value = false;
  proxy.$nextTick(() => {
    if (IsEmpty(dictList.find((item) => item.id == dictForm.id))) {
      dictRowClick({ row: dictList[0] }); //默认选中第一条数据
    } else {
      dictRowClick({ row: dictList.find((item) => item.id == dictForm.id) }); //默认选中第一条数据
    }
  });
}

/**
 * 设计模式/预览模式切换 切换预览模式
 */
function showDetailData() {
  isDictShow.value = false;
  isDetailShow.value = true;
}

/**
 * 获取设计模式table数据
 */
function findDictList() {
  dictList.length = 0;
  clearForm();
  if (IsEmpty(sltDict)) {
    return;
  }
  tloading.value = true;
  const url = '/wk/calc/base/list';
  proxy.$http
    .get(url, { params: { pid: sltDict.id, grade: 1 } })
    .then((res: any) => {
      dictList.push(...res.data);
      findDictDetailList();
      dictRowClick({ row: dictList[0] });
      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
    });
}

function formatUser(userId: any) {
  const user = userList.find(item => item.id == userId);
  if (user != undefined) {
    return user.realname;
  }
}

/**
 * 点击设计模式表格当前行触发右侧表单变化
 * @param row
 */
function dictRowClick({ row }: any) {
  addDictForm(); //在点击当前行表格数据获取右侧表单前 先清空之前表单校验+数据
  if (IsEmpty(row)) {
    clearForm();
  } else {
    (proxy.$refs.dictTable as any).setCurrentRow(row);
    setDictForm(row);
  }
}

/**
 * 清空设计模式表单
 */
function clearForm() {
  dictForm.id = null;
  dictForm.pid = '';
  dictForm.orgId = '';
  dictForm.code = '';
  dictForm.name = '';
  dictForm.grade = 1;
  dictForm.sx = 1;
  dictForm.value = '';
  dictForm.bz = '';
  dictForm.classify = '';
  dictForm.isParentEdit = '';
  dictForm.dict = '';
  dictForm.dictValue = '';
  dictForm.fieldType = '';
}

/**
 * 设计模式表单变化
 * @param row
 */
function setDictForm(row: any) {
  dictForm.code = row.code;
  dictForm.id = row.id;
  dictForm.grade = row.grade;
  dictForm.isParentEdit = row.isParentEdit;
  dictForm.name = row.name;
  dictForm.pid = row.pid;
  dictForm.sx = row.sx;
  dictForm.orgId = row.orgId;
  dictForm.value = row.value;
  dictForm.bz = row.bz;
  dictForm.classify = row.classify;
  dictForm.dict = row.dict;
  dictForm.dictValue = row.dictValue;
  dictForm.fieldType = row.fieldType;
  if (dictForm.classify == '4' && dictForm.correTable != '') {
    getTableColumns();
  }
}

// 删除选中字段的属性
function deleteDict(row: any) {
  proxy
    .$confirm('确定删除此属性？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const url = '/wk/calc/base/delete';
      proxy.$http.post(url, row).then((res: any) => {
        if (res.status.code === 1) {
          findDictList();
          VxeMessage('删除属性成功', VxeNotifyType.success);
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
      });
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

// 新建设计模式右侧表单
function addDictForm() {
  clearForm();
  if (dictList.findIndex((item) => item.code == 'isEdit') > -1) {
    dictForm.sx = dictList.length;
  } else {
    dictForm.sx = dictList.length + 1;
  }

  (proxy.$refs.dictTable as any).clearCurrentRow();
  (proxy.$refs.dictFormRef as any).resetFields();//重置该表单项，将其值重置为初始值，并移除校验结果
}

// 设计模式 右侧表单保存 (设置字段 最右侧表单保存)
function saveDict(formName: any) {
  saveFormLoading.value = true;
  let $el = proxy.$refs[formName];
  $el.validate((valid: any) => {
    if (!valid) {
      saveFormLoading.value = false;
      return false;
    }
    if (dictForm.id === null) {
      const user = {
        pid: sltDict.id,
        code: dictForm.code,
        name: dictForm.name,
        grade: 1,
        sx: dictForm.sx,
        bz: dictForm.bz,
        classify: dictForm.classify,
        dict: dictForm.dict,
        dictValue: dictForm.dictValue,
        fieldType: dictForm.fieldType,
        orgId: !isEmpty(dictForm.orgId) ? dictForm.orgId : store.userInfo.orgId
      };
      // console.log(JSON.stringify(user));
      proxy.$http.post('/wk/calc/base/add', user).then((res: any) => {
        VxeMessage('新增属性成功', VxeNotifyType.success);
        clearForm();
        findDictList();
        saveFormLoading.value = false;
      }).catch((err: any) => {
        VxeMessage('新增属性失败', VxeNotifyType.error);
        saveFormLoading.value = false;
      });
    } else {
      const user = {
        id: dictForm.id,
        code: dictForm.code,
        name: dictForm.name,
        sx: dictForm.sx,
        bz: dictForm.bz,
        classify: dictForm.classify,
        dict: dictForm.dict,
        dictValue: dictForm.dictValue,
        fieldType: dictForm.fieldType
      };
      proxy.$http.post('/wk/calc/base/update', user).then((res: any) => {
        VxeMessage('修改属性成功', VxeNotifyType.success);
        setTimeout(() => {
          clearForm();
          findDictList();
        }, 500);
        saveFormLoading.value = false;
      }).catch((err: any) => {
        VxeMessage('修改属性失败', VxeNotifyType.success);
        saveFormLoading.value = false;
      });
    }
  });
}

// 获取预览模式表格数据
function findDictDetailList() {
  lookLoading.value = true;
  detailList.length = 0; //放入数据前清空数据
  const url = '/wk/calc/base/detail/page';
  proxy.$http.get(url, { params: { pid: sltDict.id } }).then((res: any) => {
    detailList.push(...res.data);
    lookLoading.value = false;
  }).catch((err: any) => {
    lookLoading.value = false;
    VxeMessage('获取预览模式列表异常', VxeNotifyType.error);
  });
}

// 预览模式——新建字典值
function addDetail() {
  if (dictList.length > 0) {
    const row: any = {};
    for (const item of dictList) {
      row[item.code] = '';
    }
    row.isEdit = '0';
    row.isParentEdit = sltDict.isEdit;
    row.sx = detailList.length == 0 ? 1 : Number(detailList[detailList.length - 1].sx) + 1;
    detailList.push(row);
  } else {
    VXETable.modal.message({ content: '请选择基础字典', status: 'error' });
  }
}

// 预览模式最上层工具栏的保存按钮
async function saveDetailList() {
  saveLoading.value = true;
  // 获取表格实例
  let $Xtable = proxy.$refs.detailTable;
  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
      return p.commonId && p.commonId !== '';
    });
    // 拿到数组中没有id的数据为新增
    const InsertRecords = detailList.filter((e: any) => {
      return !e.commonId || e.commonId === '';
    });

    // 遍历发起请求  将筛选出有id的每一个对象（修改过的） 作为参数传递给后端
    const updateItems = [] as any[];
    updateRecords.forEach((e: any) => {
      let moduleAddParam = e;
      for (const item of dictList) {
        const itemTemp = JSON.parse(JSON.stringify(item));
        itemTemp.value = moduleAddParam[item.code];
        itemTemp.sx = moduleAddParam.sx;
        itemTemp.id = '';
        itemTemp.pid = item.id;
        itemTemp.grade = moduleAddParam.grade;
        itemTemp.orgId = store.userInfo.orgId;
        itemTemp.commonId = moduleAddParam.commonId;
        updateItems.push(itemTemp);
      }
    });

    // 新增
    const saveItems = [] as any[];
    InsertRecords.forEach((e: any) => {
      const moduleAddParam = e;
      for (const item of dictList) {
        const itemTemp = JSON.parse(JSON.stringify(item));
        itemTemp.value = moduleAddParam[item.code];
        itemTemp.sx = moduleAddParam.sx;
        itemTemp.id = '';
        itemTemp.pid = item.id;
        itemTemp.grade = 2;
        itemTemp.orgId = store.userInfo.orgId;
        saveItems.push(itemTemp);
      }
    });

    //批量一起新增
    const obj = {
      addList: saveItems,
      updateList: updateItems
    };
    // console.log(JSON.stringify(obj));
    if (saveItems.length > 0 || updateItems.length > 0) {
      proxy.$http.post('/wk/calc/base/detail/option', obj).then((res: any) => {
        if (res.status.code === 1) {
          VxeMessage(res.status.msg, VxeNotifyType.success);
          findDictDetailList();
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
        saveLoading.value = false;

      })
        .catch((err: any) => {
          saveLoading.value = false;

          VxeMessage('更新字典值异常', VxeNotifyType.error);
        });
    } else {
      saveLoading.value = false;
      VxeMessage('无添加或修改数据', VxeNotifyType.error);
    }
  } else {
    return;
  }
}

// 删除预览模式某一行的字典值
function deleteDetail(row: any) {
  proxy
    .$confirm('确定删除此字典值数据？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
    const url = '/wk/calc/base/detail/delete';
    if (row.commonId) {
      proxy.$http.post(url, row).then((res: any) => {
        if (res.status.code === 1) {
          VxeMessage('删除字典值成功', VxeNotifyType.success);
        } else {
          VxeMessage('删除字典值失败', VxeNotifyType.error);
        }
        findDictDetailList(); //重新获取预览模式表格数据
      });
    } else {
      // 删除的新增的空白数据 不走接口
      const $table = detailTable.value;
      if ($table) {
        await $table.remove(row);
        detailList.splice(row.sx - 1);
        VxeMessage('删除成功', VxeNotifyType.success);
      }
    }
  })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

// ------------------------------------------------------------
//**判断为空*/
function IsEmpty(value: any) {
  if (value === undefined || value === '' || value === null) {
    return true;
  }
  if (JSON.stringify(value) === '{}') {
    return true;
  }
  return false;
}

function panduanIsEdit(row: any) {
  if (row.commonId == undefined) {
    return true;
  } else {
    if (row.isEdit == undefined) {
      return row.isParentEdit == '0';
    } else {
      if (!(row.isParentEdit == '0')) {
        return false;
      } else {
        return row.isEdit == '0';
      }
    }
  }
}


function focusEvent() {
  tableData.length = 0;

  const $pulldown = proxy.$refs.pulldownRef;
  if ($pulldown) {
    tableData.push(...tableList);
    $pulldown.showPanel();
  }
}

// 获取设计模式 选择字典
function getTableColumns() {
  correColumnList.length = 0; //放入数据前清空数据
  const url = '/wk/calc/baseTable/getTableColumns';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { tableName: dictForm.correTable } })
    .then((res: any) => {
      correColumnList.push(...res.data);
    })
    .catch((err: any) => {
      // VxeMessage('获取获取设计模式选择字典失败',VxeNotifyType.error)
    });
}

// 获取可选的字典
function getTableDataList(row: any) {
  const columNameList = [];
  columNameList.push(row.correColumn);
  columNameList.push(row.correColumn2);
  // console.log(row);

  tableDataList.length = 0; //放入数据前清空数据
  const url = '/wk/calc/baseTableField/getTableFieldAndDataList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { tableName: row.correTable, columNameList: columNameList.join(',') } })
    .then((res: any) => {
      tableDataList.push(...res.data);
    })
    .catch((err: any) => {
      // VxeMessage('获取可选的字典失败',VxeNotifyType.error)
    });
}

function selectTableData($event, item, row) {
  const tableData = tableDataList.find((tData) => tData[item.correColumn] == $event.value);
  row[item.correField] = tableData[item.correColumn2];
}
</script>

<style lang='scss' scoped>
#CalcBaseForm {
  height: 100%;
  // 附加按钮间距
  .button-blue {
    margin: 5px 0 5px 5px;
  }

  // 设计模式表格 预览模式表格
  .designTable,
  .previewTable {
    height: calc(100% - 40px);
  }
}
</style>
